package com.xh.demo.common.utils;

import com.xh.demo.common.enums.ErrorEnum;
import com.xh.demo.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Name DateUtil
 * @Description
 * @Author wen
 * @Date 2019-08-01
 */
@Slf4j
public class DateUtil {

    public static final SimpleDateFormat[] formarters = new SimpleDateFormat[4];

    public static final String DATE_FORMART_01 = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_FORMART_02 = "yyyy-MM-dd";

    public static final String DATE_FORMART_03 = "yyyy/MM/dd HH:mm:ss";

    public static final String DATE_FORMART_04 = "yyyy/MM/dd";

    static {
        formarters[0] = new SimpleDateFormat(DATE_FORMART_01);
        formarters[1] = new SimpleDateFormat(DATE_FORMART_02);
        formarters[2] = new SimpleDateFormat(DATE_FORMART_03);
        formarters[3] = new SimpleDateFormat(DATE_FORMART_04);
    }

    /**
    * @Name parseDate
    * @Description 通用String To Date转换器(支持以上四种格式)
    * @Author wen
    * @Date 2019/8/2
    * @param source
    * @return java.util.Date
    */
    public static Date parseDate(String source){
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return parseDate(source, formarters[0]);
        }
        if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            return parseDate(source, formarters[1]);
        }
        if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return parseDate(source, formarters[2]);
        }
        if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$")) {
            return parseDate(source, formarters[3]);
        }
        throw new BusinessException(ErrorEnum.DATE_PARAMETER_ERROR);
    }

    /**
     * 格式化日期
     * @param dateStr String 字符型日期
     * @param formater SimpleDateFormat
     * @return Date 日期
     */
    private static Date parseDate(String dateStr, SimpleDateFormat formater) {
        Date date = null;
        try {
            date = formater.parse(dateStr);
        } catch (Exception e) {
            log.error("日期格式化失败:", e);
        }
        return date;
    }

}
